package com.jsgt.greekfire.ui.trading.otc

import android.app.Dialog
import android.content.DialogInterface
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseFragment
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.R
import com.jsgt.greekfire.bean.MyOrderBean
import com.jsgt.greekfire.common.util.RecycleEmptyView
import com.jsgt.greekfire.common.util.XLinearLayoutManager
import com.jsgt.greekfire.dialog.CommonDialog
import com.jsgt.greekfire.factory.OTCTraddingModelFactory
import com.jsgt.greekfire.ui.gfc.adapter.CommissionAdapter
import com.jsgt.greekfire.ui.gfc.adapter.UserAdAdapter
import com.jsgt.greekfire.viewmodel.OTCTraddingViewModel
import com.scwang.smartrefresh.header.MaterialHeader
import kotlinx.android.synthetic.main.fragment_commission.*


private const val ARG_PARAM1 = "param1"

class OTCCommissionFragment : BaseFragment() {
    private var param1: Int? = null
    var orderList: ArrayList<MyOrderBean.ListBean>? = ArrayList()
    var completedOrderList: ArrayList<MyOrderBean.ListBean>? = ArrayList()
    var cancelledOrderList: ArrayList<MyOrderBean.ListBean>? = ArrayList()

    var ivDialogClosed: ImageView? = null
    var tRvecall: TextView? = null
    var cancel: TextView? = null
    private var page = 1
    private var page1 = 1
    private var page2 = 1
    private var limit = 10
    private var dealType = ""  //类型 1卖出 2买入
    private var dealState = 1  //广告状态 1上架中 0下架
    private val otcTraddingViewModel: OTCTraddingViewModel by lazy {
        ViewModelProvider(
            this,
            OTCTraddingModelFactory()
        ).get(OTCTraddingViewModel::class.java)
    }

    private val commissionAdapter by lazy {

        CommissionAdapter(context!!, R.layout.item_commission_list)
    }
    private val userAdAdapter by lazy {

        UserAdAdapter(context!!, R.layout.item_commission_order_list)
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: Int) =
            OTCCommissionFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_PARAM1, param1)
                }
            }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getInt(ARG_PARAM1, -1)
        }
    }


    override fun getLayoutId(): Int = R.layout.fragment_commission
    override fun main() {

        refreshCommission.autoRefresh()
        refreshCommission.setRefreshHeader(MaterialHeader(context));
        refreshCommission.setOnRefreshListener {
            if (param1 == 0) {
                page = 1;
                otcTraddingViewModel.getUserAd(dealType, dealState, limit, page)
            } else if (param1 == 1) {
                page1 = 1;
                otcTraddingViewModel.getUserOrderData(page1)
            } else if (param1 == 2) {
                page2 = 1;
                otcTraddingViewModel.getUserAd(dealType, 0, limit, page2)
            }
        }
        refreshCommission.setOnLoadMoreListener {
            if (param1 == 0) {
                ++page
                otcTraddingViewModel.getUserAd(dealType, dealState, limit, page)
            } else if (param1 == 1) {
                ++page1
                otcTraddingViewModel.getUserOrderData(page1)
            } else if (param1 == 2) {
                ++page2
                otcTraddingViewModel.getUserAd(dealType, 0, limit, page2)
            }
        }
        rvCommission.layoutManager = XLinearLayoutManager(context)
        if (param1 == 1) {
            rvCommission.adapter = userAdAdapter
            userAdAdapter.setNewData(completedOrderList)
            userAdAdapter.setOnItemClickListener { adapter, view, position ->
                // showCommissionDialog(userAdAdapter.data.get(position).guid.toString());
            }
        } else {
            rvCommission.adapter = commissionAdapter
            commissionAdapter.setNewData(orderList)
            commissionAdapter.setOnItemClickListener { adapter, view, position ->
//            showCommissionDialog(commissionAdapter.data.get(position));
            }
        }
        commissionAdapter.addChildClickViewIds(R.id.tvRemoval)
        commissionAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.tvRemoval) {
                CommonDialog.Builder(context!!)
                    .setMessage(context!!.resources.getString(R.string.otc_text_order_removal1))
                    .setNegativeButton(
                        context!!.resources.getString(R.string.otc_text_order_confirm),
                        DialogInterface.OnClickListener { dialog, which ->
                            dialog.dismiss()
                            if (!TextUtils.isEmpty(commissionAdapter.data.get(position).guid.toString())) {
                                showProgress(true)
                                otcTraddingViewModel.cancellationOrders(
                                    commissionAdapter.data.get(
                                        position
                                    ).guid.toString()
                                )

                            }
                        })
                    .setMessageColor(Color.BLACK)
                    .setPositiveButton(
                        context!!.resources.getString(R.string.otc_text_order_cance),
                        DialogInterface.OnClickListener { dialog, which ->
                            dialog.dismiss()
                        }
                    )
                    .setWith(0.8f)
                    .create()
                    .show()
            }
        }
        otcTraddingViewModel.userOrderData.observe(this, Observer {
            if (it.result != null) {
                if (param1 == 1) {
                    if (page1 == 1) {
                        completedOrderList!!.clear()
                    }
                    completedOrderList!!.addAll(it.result?.list!!)
                    userAdAdapter.notifyDataSetChanged()
                }
                if (it.result?.list!!.size < limit) {
                    refreshCommission.finishLoadMoreWithNoMoreData();
                } else {
                    refreshCommission.finishLoadMore();
                }
            } else {
                refreshCommission.finishLoadMoreWithNoMoreData();
            }

            if (completedOrderList!!.size <= 0) {
                RecycleEmptyView.showEmptyView(
                    activity as AppCompatActivity?,
                    userAdAdapter,
                    "暂无订单",
                    R.mipmap.icon_empty_no_data
                )
            }
        })
        otcTraddingViewModel.userAdData.observe(this, Observer {
            if (it.result != null) {
                if (param1 == 0) {
                    if (page == 1) {
                        orderList!!.clear()
                    }
                    orderList!!.addAll(it.result?.list!!)
                    commissionAdapter.notifyDataSetChanged();
                    if (orderList!!.size <= 0) {
                        RecycleEmptyView.showEmptyView(
                            activity as AppCompatActivity?,
                            commissionAdapter,
                            "暂无订单",
                            R.mipmap.icon_empty_no_data
                        )
                    }

                } else if (param1 == 2) {
                    if (page2 == 1) {
                        cancelledOrderList!!.clear()
                    }
                    cancelledOrderList!!.addAll(it.result?.list!!)
                    commissionAdapter.setList(cancelledOrderList!!)
                    if (cancelledOrderList!!.size <= 0) {
                        RecycleEmptyView.showEmptyView(
                            activity as AppCompatActivity?,
                            commissionAdapter,
                            "暂无订单",
                            R.mipmap.icon_empty_no_data
                        )
                    }

                }
                if (it.result?.list!!.size < limit) {
                    refreshCommission.finishLoadMoreWithNoMoreData();
                } else {
                    refreshCommission.finishLoadMore();
                    refreshCommission.finishRefresh(true);
                }

            } else {
                refreshCommission.finishLoadMoreWithNoMoreData();
            }

        })
        otcTraddingViewModel.adDownData.observe(this, Observer {
            showProgress(false)
            ToastUtils.show(context!!.resources.getString(R.string.submitted))
            if (refreshCommission != null) {
                refreshCommission.autoRefresh()
            }
        })
        otcTraddingViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
            showToast(it.toString())
            if (param1 == 0) {
                if (orderList!!.size <= 0) {
                    if (page > 1) {
                        page--;
                        refreshCommission.finishLoadMore(false);
                    }
                }
            } else if (param1 == 1) {
                if (completedOrderList!!.size <= 0) {
                    if (page1 > 1) {
                        page1--;
                        refreshCommission.finishLoadMore(false);
                    }
                }
            } else if (param1 == 2) {
                if (cancelledOrderList!!.size <= 0) {
                    if (page2 > 1) {
                        page2--;
                        refreshCommission.finishLoadMore(false);
                    }
                }
            }
            refreshCommission.finishRefresh();

        })
    }

    /**
     * 选择展示设置
     */
    private fun showCommissionDialog(guid: String) {
        val button1Dialog: Dialog = Dialog(context!!, R.style.DialogTheme)
        val view: View = LayoutInflater.from(context!!).inflate(R.layout.dialog_commission, null)
        button1Dialog.setContentView(view)
        var layoutParams: ViewGroup.LayoutParams = view.layoutParams
        layoutParams.width = resources.displayMetrics.widthPixels
        view.layoutParams = layoutParams
        button1Dialog.window!!.setGravity(Gravity.BOTTOM)
        button1Dialog.window!!.setWindowAnimations(R.style.main_menu_animStyle)
        button1Dialog.show()

        ivDialogClosed = view.findViewById(R.id.ivDialogClosed)
        tRvecall = view.findViewById(R.id.tRvecall)
        cancel = view.findViewById(R.id.cancel)

        ivDialogClosed?.setOnClickListener { v ->
            button1Dialog.dismiss()
        }
        tRvecall?.setOnClickListener { v ->
            showProgress(true)
            if (!TextUtils.isEmpty(guid)) {
                otcTraddingViewModel.cancellationOrders(guid)
            }
            button1Dialog.dismiss()
        }
        cancel?.setOnClickListener { v ->
            button1Dialog.dismiss()
        }


    }

}